package com.libinyn.base.pms.serivce.impl.sys;


import com.libinyn.base.pms.common.exception.PmsException;
import com.libinyn.base.pms.common.utils.Constant;
import com.libinyn.base.pms.entity.sys.SysUserEntity;
import com.libinyn.base.pms.mapper.sys.SysUserMapper;
import com.libinyn.base.pms.serivce.impl.BaseServiceImpl;
import com.libinyn.base.pms.serivce.sys.SysRoleService;
import com.libinyn.base.pms.serivce.sys.SysUserRoleService;
import com.libinyn.base.pms.serivce.sys.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 系统用户
 * @fileName: SysUserServiceImpl.java
 * @author: bin.li01
 * @date: 2017/12/10 17:09 
 * @version: v1.0.0
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserEntity> implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private SysUserRoleService sysUserRoleService;
	@Resource
	private SysRoleService sysRoleService;


	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return sysUserMapper.queryAllMenuId(userId);
	}

	@Override
	public void save(SysUserEntity user) {
//		user.setCreateTime(new Date());
//		//sha256加密
//		String salt = RandomStringUtils.randomAlphanumeric(20);
//		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
//		user.setSalt(salt);
//		sysUserMapper.insert(user);
//
//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void updateUser(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		sysUserMapper.updateByPrimaryKeySelective(user);
		
//		//检查角色是否越权
//		checkRole(user);
//
//		//保存用户与角色关系
//		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userIds) {
		sysUserMapper.deleteBatch(userIds);
	}

	@Override
	public int updatePassword(Long userId, String password, String newPassword) {

		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", password);
		map.put("newPassword", newPassword);
		return sysUserMapper.updatePassword(map);
	}
	
	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateBy() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateBy());
		
		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new PmsException("新增用户所选角色，不是本人创建");
		}
	}
}
